<?php

namespace Xiaoc\Api;
/**
 * Xiaoc用户登录/退出/注册
 *
 * @author: whs
 */
class Login extends Common
{
    public function getRules()
    {
        $data['Login'] = array(
            'username' => array('name' => 'username', 'desc' => '用户名', 'require' => true),
            'password' => array('name' => 'password', 'desc' => '密码', 'require' => true),
        );
        $data['Register'] = array(
            'mobile' => array('name' => 'mobile', 'desc' => '手机号', 'require' => true),
            'password' => array('name' => 'password', 'desc' => '密码', 'require' => true),
            'confirm_password' => array('name' => 'confirm_password', 'desc' => '确认密码', 'require' => true),
            'code' => array('name' => 'code', 'desc' => '短信验证码', 'require' => true),
            'openid' => array('name' => 'openid', 'desc' => '第三方登录的openId'),
            'referrer' => array('name' => 'referrer ', 'desc' => '推荐人手机号'),
        );
        $data['SendCode'] = array(
            'mobile' => array('name' => 'mobile', 'desc' => '手机号', 'require' => true),
            'type' => array('name' => 'type', 'desc' => '类型', 'require' => true, 'desc' => '1修改密码2注册3设置支付密码4其他操作', 'default' => 4),
        );
        $data['qq_login'] = array(
            'accessToken' => array('name' => 'accessToken', 'desc' => 'qq的token值', 'require' => true),
            'appid' => array('name' => 'appid', 'desc' => 'app需要传配置项的appid')
        );
        $data['user_bind'] = array(
            'username' => array('name' => 'username', 'desc' => '用户名', 'require' => true),
            'password' => array('name' => 'password', 'desc' => '密码', 'require' => true),
            'openid' => array('name' => 'openid', 'desc' => 'openid', 'require' => true)
        );
        $data['wx_login'] = array(
            'openid' => array('name' => 'openid', 'desc' => '微信的openid', 'require' => true),
            'access_token' => array('name' => 'access_token', 'desc' => '微信的access_token', 'require' => true),
        );
        $data['forgot_password'] = array(
            'password' => array('name' => 'password', 'desc' => '密码', 'require' => true),
            'confirm_password' => array('name' => 'confirm_password', 'desc' => '确认密码', 'require' => true),
            'code' => array('name' => 'code', 'desc' => '短信验证码', 'require' => true),
            'mobile' => array('name' => 'mobile', 'desc' => '手机号', 'require' => true),
        );
        $data['OutLogin'] = array(
            'user_token' => array('name' => 'user_token', 'desc' => '用户token', 'require' => true),
        );
        return $data;
    }

    /**
     * 会员登录
     * @desc    会员登录
     * @return string user_token TOKEN值
     */
    public function Login()
    {
        $username = $this->username;
        $password = $this->password;
        if (isMobile($username)) {
            $where['mobile_phone'] = $username;
        } elseif (isEmail($username)) {
            $where['email'] = $username;
        } else {
            $where['user_name'] = $username;
        }
        $fieds = array('user_id', 'password', 'visit_count', 'ec_salt', 'user_name');
        $res = $this->medoo->get('users', $fieds, $where);
        if ($res) {
            $cf['password'] = $password;
            $cf['ec_salt'] = $res['ec_salt'];
            $cf_password = $this->user_password($cf);
            if ($cf_password == $res['password']) {
                $tokens = $this->di->cache->get($res['user_id']);
                if ($tokens && count($tokens) > 3) {
                    $this->api_error_msg('你的账号已在多个设备登录', 1);
                }
                unset($res['password']);
                $token = $this->update_login($res);
                $data['user_token'] = $token;
                return $data;
            }
        }
        $this->api_error_msg('用户名或密码错误', 1);
    }

    /**
     *  会员退出
     * @desc 会员退出
     * User: wanghousheng
     * Date: 2016/12/27
     */
    public function OutLogin()
    {
        $token = $this->user_token;
        $user_info = $this->di->cache->get($token);
        if ($user_info) {
            $tokens = $this->di->cache->get($user_info['user_id']);
            if ($tokens) {
                foreach ($tokens as $key => $val) {
                    if ($val == $token) {
                        unset($tokens[$key]);
                    }
                }
                $tokens = array_values($tokens);
                $this->di->cache->set($user_info['user_id'], $tokens, 3600 * 24 * 365);
                $this->di->cache->delete($token);
                $this->api_success_msg('注销成功');
            }

        }
        $this->api_error_msg('注销失败');

    }

    /**
     * 会员注册
     * @desc    会员注册
     * @return string user_token TOKEN值
     */
    public function Register()
    {
        $mobile = $this->mobile;
        $password = $this->password;
        $code = $this->code;
        $openid = trim($this->openid);
        $confirm_password = $this->confirm_password;
        $referrer = $this->referrer;
        if (isMobile($mobile) && intval($code) && $password && $password == $confirm_password) {
            //检查短信验证码
            $res_code = check_code($mobile, $code);
            if (!$res_code) $this->api_error_msg('验证码错误', 1);
            //检查手机号不是存在
            $mobile_phone = $this->check_user_mobile($mobile);
            if ($mobile_phone) {
                $this->api_error_msg('该手机号已存在', 1);
            }
            $connect_status = 0;
            if ($openid) {
                $connect_info = $this->di->cache->get($openid);
                if ($connect_info && isset($connect_info['oauth_type'])) {
                    $res = $this->medoo->get('connect_user', 'id', array('open_id' => $openid, 'connect_code' => $connect_info['oauth_type']));
                    if ($res) {
                        $this->api_error_msg('该账号已绑定其他账号');
                    }
                    $connect_status = 1;
                }

            }
            if ($referrer && isMobile($referrer)) {
                $where['mobile_phone'] = trim($referrer);
                $res = $this->di->medoo->get('users', 'mobile_phone', $where);
                $p_id = $res['user_id'];
                $add['parent_id'] = $p_id;
            }
            $num = substr($mobile, -4);
            $add['mobile_phone'] = $mobile;
            $add['user_name'] = $mobile;
            $add['nick_name'] = getMemberName('XC', $num);
            $add['password'] = $this->user_password(array('password' => $password));
            $this->di->medoo->insert('users', $add);
            $user_id = $this->di->medoo->id();
            if ($user_id) {
                if ($connect_status == 1) {
                    $connect_arr['connect_code'] = $connect_info['oauth_type'];
                    $connect_arr['user_id'] = $user_id;
                    $connect_arr['open_id'] = $openid;
                    $connect_arr['profile'] = serialize($connect_info);
                    $connect_arr['create_at'] = gmtime();
                    $connect_id = $this->medoo->insert('connect_user', $connect_arr);
                    if ($connect_id) {
                        $this->di->cache->delete($openid);
                    }
                }
                //更新用户信息
                $arr['visit_count'] = 0;
                $arr['user_id'] = $user_id;
                $arr['user_name'] = $add['user_name'];
                $token = $this->update_login($arr);

                if ($token) return array('user_token' => $token);
            } else {
                $this->api_error_msg('注册失败', 1);
            }
        } else {
            $this->api_error_msg('参数有误', 1);
        }
    }

    /**
     * 发送短信验证码
     * @desc    发送短信验证码
     * @return bool
     */
    public function SendCode()
    {
        $mobile = $this->mobile;
        $type = $this->type;
        if ($mobile && $type && in_array($type, array('1', '2', '3', '4'))) {
            if ($type == 2) {
                $mobile_phone = $this->check_user_mobile($mobile);
                if ($mobile_phone) {
                    $this->api_error_msg('该手机号已存在', 1);
                }
            }
            if ($type == 1 || $type == 3) {
                $mobile_phone = $this->check_user_mobile($mobile);
                if (!$mobile_phone) {
                    $this->api_error_msg('该手机号不存在', 1);
                }
            }
            $res = send_code($mobile, $type);
            if (!$res['status']) {
                $this->api_error_msg($res['message']);
            } else {
                return $this->api_success_msg('发送成功');
            }
        }
        $this->api_error_msg('参数有误', 1);
    }

    /**
     * QQ第三方登录
     * @desc   当token值为空时需要绑定账号
     * @return string user_token TOKEN值
     */
    public function qq_login()
    {
        $config = $this->get_oauth_qq();
        if ($config) {
            $appid = $this->appid;
            if ($appid) {
                $config['APIId'] = trim($appid);
            }
            $oath_obj = new \Qq_Lite($config);
            $accessToken = $this->accessToken;
            $user_info = $oath_obj->getUsrInfo($accessToken);
            if (isset($user_info['openid']) && $user_info['openid']) {
                $user_info['unionid'] ? $openid = $user_info['unionid'] : $openid = $user_info['openid'];
                $user_info['openid'] = $openid;
                $join['[>]connect_user'] = array('user_id');
                $condition['connect_user.connect_code'] = 'sns_qq';
                $condition['connect_user.open_id'] = $openid;
                $condition_field = array('users.user_id', 'users.user_name', 'users.visit_count');
                $info = $this->medoo->get('users', $join, $condition_field, $condition);
                if ($info) {
                    $token = $this->update_login($info);
                    return array('user_token' => $token);
                } else {
                    //保存信息至缓存
                    $user_info['oauth_type'] = 'sns_qq';
                    $this->di->cache->set($openid, $user_info, 120);
                    return array('user_token' => '', 'openid' => $openid);
                }
            } else {
                $this->api_error_msg('授权失败', 1);
            }
        } else {
            $this->api_error_msg('平台已关闭该登录方式', 1);
        }
    }

    /**
     * 第三方登录绑定账号
     * @desc    第三方登录绑定账号
     * @return string user_token TOKEN值
     */
    public function user_bind()
    {
        $openid = $this->openid;
        $user_name = $this->username;
        $password = $this->password;
        if ($openid) {
            $user_info = $this->di->cache->get($openid);
            if ($user_info) {
                if (isMobile($user_name)) {
                    $where['mobile_phone'] = $user_name;
                } elseif (isEmail($user_name)) {
                    $where['email'] = $user_name;
                } else {
                    $where['user_name'] = $user_name;
                }
                $fieds = array('user_id', 'password', 'visit_count', 'ec_salt', 'user_name');
                $res = $this->medoo->get('users', $fieds, $where);
                if ($res) {
                    $cf['password'] = $password;
                    $cf['ec_salt'] = $res['ec_salt'];
                    $cf_password = $this->user_password($cf);
                    if ($cf_password == $res['password']) {
                        $connect_where['connect_code'] = $user_info['oauth_type'];
                        $connect_where['user_id'] = $res['user_id'];
                        $connect_where['open_id'] = $user_info['openid'];
                        $res_connect = $this->medoo->get('connect_user', array('id'), $connect_where);
                        if (empty($res_connect)) {
                            $connect_where['profile'] = serialize($user_info);
                            $connect_where['create_at'] = gmtime();
                            $this->medoo->insert('connect_user', $connect_where);
                            $connect_id = $this->medoo->id();
                            if ($connect_id) {
                                $this->di->cache->delete($openid);
                                $token = $this->update_login($res);
                                return array('user_token' => $token);
                            }
                        } else {
                            $this->api_error_msg('该账号已绑定其他账号', 1);
                        }
                    } else {
                        $this->api_error_msg('用户名或密码错误', 1);
                    }
                } else {
                    $this->api_error_msg('用户名或密码错误', 1);
                }
            } else {
                $this->api_error_msg('授权信息获取失败', 1);
            }
        }
    }

    /**
     * 微信第三方登录
     * @desc    当token值为空时需要绑定账号
     * @return string user_token TOKEN值
     */
    public function wx_login()
    {
        $where['type'] = 'wechat';
        $where['status'] = 1;
        $oauth = $this->medoo->get('touch_auth', array('auth_config'), $where);
        if (empty($oauth)) $this->api_error_msg('平台已关闭该登录方式', 1);
        $obj = new \Wx_Lite(array());
        $user_info = $obj->getUserInfo($this->access_token, $this->openid);
        if ($user_info['status'] && $user_info['data']) {
            $user_info = $user_info['data'];
        } else {
            $this->api_error_msg('授权失败');
        }
        $join['[>]connect_user'] = array('user_id');
        $condition['connect_user.connect_code'] = 'sns_wechat';
        $condition['connect_user.open_id'] = $user_info['openid'];
        $condition_field = array('users.user_id', 'users.user_name', 'users.visit_count');
        $info = $this->medoo->get('users', $join, $condition_field, $condition);
        if ($info) {
            $token = $this->update_login($info);
            return array('user_token' => $token);
        } else {
            //保存信息至缓存
            $user_info['oauth_type'] = 'sns_wechat';
            $this->di->cache->set($user_info['openid'], $user_info, 120);
            return array('user_token' => '', 'openid' => $user_info['openid']);
        }
    }

    /**
     * 忘记密码
     * @desc    忘记密码
     * @return string ret 200成功
     */
    public function forgot_password()
    {
        $mobile = $this->mobile;
        $password = $this->password;
        $code = $this->code;
        $confirm_password = $this->confirm_password;
        if ($confirm_password && $confirm_password == $password && isMobile($mobile) && $code) {
            $res_code = check_code($mobile, $code);
            if ($res_code) {
                $where['mobile_phone'] = $mobile;
                $fieds = array('password', 'ec_salt');
                $res = $this->medoo->get('users', $fieds, $where);
                if ($res) {
                    $up['password'] = $this->user_password(array('password' => $password, 'ec_salt' => $res['ec_salt']));
                    $return = $this->medoo->update('users', $up, $where);
                    if ($return) {
                        $this->api_success_msg('修改成功');
                    } else {
                        $this->api_error_msg('修改失败', 1);
                    }
                }
            } else {
                $this->api_error_msg('验证码错误');
            }
        }
    }
}